<?php
/**
 * 店铺管理
 * @author ezhu <ezhu@jipukeji.com>
 */
namespace Admin\Controller;

class StoreController extends AdminController{
    
    /**
     *  可销售区域
     */
    public function available_zone(){
        $model = M('Zone_used');
        if(IS_POST){
            $data = array(
                'store_id' => I('store_id'), 
                'areas'    => implode(',' ,I('zone')),
                'mtime'    => time(),
            );
            if(I('id')){
                $map['id'] = I('id');
                //查询是否进行更改操作
                if (empty(I('zone'))) {
                    $this->error('店铺可售区域不能为空！');
                }
                $old_areas = $model->where($map)->getField('areas');
                if ($old_areas == $data['areas']) {
                    $this->error('数据未更改，请重新编辑！');
                }
                $res = $model->where($map)->save($data);
                if ($res) {
                   $where['store_id'] = $data['store_id'];
                   $where['status'] = 1;
                   M('Item')->where($where)->setField('status',0);
                   //店铺通知信息
                   $cdata = array(
                        'uid' => UID,
                        'to_store' => $data['store_id'],
                        'title' => '店铺可销售区域变动通知',
                        'content' => '由于店铺可销售区域发生变动，您店铺内所有商品已经下架，请重新登陆设置上架处理。给你带来的不便，敬请谅解！',
                        'status' => 1,
                        'ctime' => NOW_TIME
                    );
                   M('StoreMessage')->add($cdata); 
                   $this->success('更新成功！');
                }else{
                    $this->error('更新失败，请稍候再试');
                }
            }else{
                $model->add($data) ? $this->success('添加成功' ): $this->error('添加失败，请稍候再试');
            }
            exit();
        }else{
            $info =$model->where('store_id = '.I('id'))->field('id ,areas')->find();
        }
        if(!I('id'))$this->error('数据错误');
        // $aIds   = I('aIds');//已选城市
        $curIds = $info['areas'];//当前城市
        $this->id = $info['id'];
        $all_ids = explode(',',$aIds);
        $cur_ids = explode(',', $curIds);
        $hasIds  = array_diff($all_ids,$cur_ids);
        $this->store_id = I('id');
        $zone = D('Shop/Area')->myZone($hasIds,$cur_ids);
        $this->assign('curIds',$cur_ids);
        $this->assign('hasIds',$hasIds);
        $this->assign('zone',$zone);
        $this->meta_title='可销售区域设置';
        $this->is_edit = (empty($hasIds)) ? '0' : '1';
        $this->display();
    }
    
    /**
     * 店铺列表
     */
    public function index(){
        $map = array();
        $status = I('get.status');
        $map['status'] = array('egt',0);
        $_GET['store']  && $map['store_name'] = array('like','%'.I('get.store').'%');
        $_GET['seller'] && $map['seller_name'] = array('like','%'.I('get.seller').'%');
        if($_GET['grade']){
            $map['grade_id'] = array('eq',I('get.grade'));
        }
        if($status != '' && $status != 'all' && in_array($status, array(-1,0,1))){
            $map['status'] = array('eq',$status);
        }
        //15天之内的算是即将到期
        $etimeLimit = time()+1296000;
        $status == 2 && $map['end_time'] = array(array('egt',time()),array('lt',$etimeLimit));
        $status == 3 && $map['_string'] = '`end_time`>0 AND `end_time`<'.time();
        
        $order = 'time desc';
        $field = array('store_id','member_id','store_name','grade_id','member_name','seller_name','tel','end_time','status');
        $grade = M('store_grade')->field('id,name')->order('sort desc')->select();
        $newArr = array();
        foreach ($grade as $key=>$val){
            $newArr[$val['id']] = $val['name'];
        }
        $this->assign('grade',$newArr);
        $lists = $this->lists(CONTROLLER_NAME, $map,$order,$field);
        //记录当前列表页的Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $statusArr = array(
            '0' => '<span class="text-cancel">已禁用</span>',
            '1' => '<span class="text-success">正常</span>',
            '2' => '<span class="text-warning">即将到期</span>',
            '3' => '<span class="text-danger">已到期</span>'
        );
        foreach ($lists as $key=>$val){
            $lists[$key]['status_text'] = $statusArr[$val['status']];
            
            if($val['end_time'] >= time() && $val['end_time'] < $etimeLimit){
                $lists[$key]['status_text'] = $statusArr[2];
            }else if(!empty($val['end_time']) && $val['end_time'] < time()){
                $lists[$key]['status_text'] = $statusArr[3];
            }
            //查询是否存在店铺地址修改 申请 BUDDHA
            $is_edit = M('Store_edit_address')->where(array('member_id'=>$val['member_id'],'status'=>0))->count();
            $is_exist = M('Store_edit_address')->where(array('member_id'=>$val['member_id'],'status'=>array('neq',0)))->count();
            $lists[$key]['is_edit'] = $is_edit;
            $lists[$key]['is_exist'] = $is_exist;
        }
        //display前置操作
        $this->lists = $lists;
        $this->meta_title = '店铺列表';
        $this->display();
    }

    /**
     * 店铺详细地址
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function storeAddress(){
        if (IS_POST) {
            //$cdata['company_address'] = I('post.address');
            $province = M('Area')->getFieldById(I('post.province'),'sub_name');
            $district = M('Area')->getFieldById(I('post.district'),'sub_name');
            $city     = M('Area')->getFieldById(I('post.city'),'title');

            $data['company_address']  = $province.' '.$district.' '.$city; 
            $data['company_address_detail'] = I('post.address_detail');
            
            $member_id = I('post.member_id');
            $rst = M('StoreApply')->where(array('member_id'=>$member_id))->save($data);               
            if($rst !== false){
                $this->success('店铺地址更新成功！',U('index'));
            }else{
                $this->error('店铺地址更新失败！');
            }
        }
        $member_id = I('get.id');
        $data = getStoreLatLng($member_id);
        //查询店铺原来信息
        $cdata = M('StoreApply')->where('member_id='.$member_id)->Field('company_address AS address,company_address_detail AS address_info')->find();
        //省市区数据修改
        $area = explode(' ',$cdata['address']);
        $arr['province'] = M('Area')->getFieldBySubName($area[0],'id');
        $arr['district'] = M('Area')->getFieldBySubName($area[1],'id');
        $arr['city'] = M('Area')->where(array('title'=>$area[2],'pid'=>$arr['district']))->getField('id');
        //查询店铺等级名称
        $data['grade_name'] = M('StoreGrade')->where('id='.$data['grade_id'])->getField('name');
        $this->arr = $arr;
        $this->data = $data;
        $this->member_id = $member_id;
        $this->meta_title = '店铺详细地址展示';
        $this->display();
        
    }

    /**
     * 店铺地址修改申请
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function storeAddressEdit(){
        $member_id = I('get.id');
        $data = M('Store_edit_address')->where('member_id='.$member_id)->find();
        //查询店铺原来地址
        $info = M('StoreApply')->where('member_id='.$member_id)->field('company_address AS address,company_address_detail AS address_detail')->find();
        $this->info=$info;
        $this->member_id=$member_id;
        $this->data = $data;
        $this->meta_title = '店铺地址修改申请';
        $this->display();
    }

    /**
     * 店铺地址修改申请处理
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function updateAddressEdit(){
        $status = trim(I('get.status'));
        $member_id = trim(I('get.id'));
        if(empty($member_id) || $status=='') $this->error('系统参数异常！');

        $data['status'] = $status;
        $data['update_time'] = NOW_TIME;

        $store_address = M('Store_edit_address');
        
        $info = $store_address->where('member_id='.$member_id)->find();

        //审核通过
        if ($status == 1) {
            //开启事务
            $store_address->startTrans();
            $res = $store_address->where('member_id='.$member_id)->save($data);

            $cdata['company_address'] = $info['address'];
            $cdata['company_address_detail'] = $info['address_detail'];

            $res1 = M('StoreApply')->where('member_id='.$member_id)->save($cdata);

            if ($res != false && $res1 != false) {
                $store_address->commit();
                $this->success('操作成功！');
            }else{
                $store_address->rollback();
                $this->error('操作失败！');
            }

        }else{
          //审核不通过  
          if ($store_address->where('member_id='.$member_id)->save($data)) {
              $this->success('操作成功！');
          }else{
             $this->error('操作失败！');
          }
        }
    }
    /**
     * 处理提现申请
     */
    public function setCashStatus($status,$id){
        $Payment = M('StoreCash');
        if(false!==M('StoreCash')->save(array('status'=>$status,'id'=>$id))){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 店铺资金流水
     */
    public function cash($keywords = null,$flow = null){
        //实例化收款单模型
        $Payment = M('StoreCash');
        $where['status']=array('ELT',2);
        //查询条件：支付编号,订单编号,店铺名称
        if($keywords){
            $payment_order=M('Order')->where(array('order_sn'=>array('LIKE','%'.$keywords.'%')))->field('payment_id')->select();
            $payment_ids=array_column($payment_order,'payment_id');
            if(!$payment_ids)$payment_ids=array(0);
            $store = M('Store')->where(array('store_name'=>array('LIKE','%'.$keywords.'%')))->field('store_id')->select();
            $store_ids = array_column($store,'store_id');
            if(!$store_ids)$store_ids=array(0);
            $where['_string'] = '(remark like "%'.$keywords.'%") OR (trade_sn in ('.implode(',',$payment_ids).') OR (store_id in ('.implode(',',$store_ids).')))';
        }
        /*     if($flow){
            $where['flow|type'] = $flow;
        }
        if($flow == 'cousume'){
            $where['flow|type'] = array('in',array('consume',' consume'));
        }*/
        if( $flow=='in+'){
            $flow = 'in';
            $where['flow|type'] = $flow;
        }else if($flow == 'cousume'){
            $where['flow|type'] = array('in',array('consume',' consume'));
        }else if($flow){
            $where['flow|type'] = $flow;
        }
       //交易类型
       $type = array(
         '用户消费'=> 'consume',
         '用户退款'=>'refund',
         '店铺促销活动费用'=>'store_cost',
         '三级分销'=>'sdp_dis',
         '分销店铺'=>'sdp_order',
         '商家提现'=>'apply'
       );
        //按条件查询结果并分页
        $list = $this->lists($Payment, $where, 'id desc');
        $store_ids=array_column($list,'store_id');
        if($list){
            $store_row=M('Store')->where(array('store_id'=>array('in',$store_ids)))->select();
            $store=array();
            foreach ($store_row as $v){
                $store[$v['store_id']]=$v;
            }
            $this->assign('store', $store);
        }
        //记录当前列表页的Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $remark=$Payment->field('distinct(remark)')->select();
        $this->assign('remark', $remark);
        //模板输出变量赋值
        $this->assign('list', $list);
        $this->assign('type',$type);
        $this->meta_title = '资金流水';
        $this->display();
    }

    /**
     * 提现申请
     */
    public function bill($keywords = null,$flow = null,$status = null){
        //实例化收款单模型
        $Payment = M('StoreWithdraw');
      //  $where = '1=1';

        if($status){
            $where['status'] = $status;
        }

        //按时间搜索
        $start_time = I('start_time','');
        $start_time = !empty($start_time) ? strtotime($start_time) : '';

        $end_time = I('end_time','');
        $end_time = !empty($end_time) ? strtotime($end_time) + 24 * 3600 : '';
        if(!empty($start_time)){
            $where[] = "`ctime` > $start_time";
        }
        if(!empty($end_time)){
            $where[] = "`ctime` < $end_time";
        }
        //按条件查询结果并分页
        $list = $this->lists($Payment, $where, 'id desc');
        foreach ($list AS $k => $v){
            //根据member_id关联
            $member_id = $member_id = M('Seller')->where(array('store_id'=>$v['store_id']))->getField('member_id');
            $store_row=M('StoreApply')->where(array('member_id'=>$member_id))->field('settlement_bank_account_name,settlement_bank_account_number')->find();
            $list[$k]['back_name']=$store_row['settlement_bank_account_name'];
            $list[$k]['back_account']=$store_row['settlement_bank_account_number'];
        }

        //记录当前列表页的Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        
        //模板输出变量赋值
        $this->status = get_store_withdraw_text();
        $this->assign('list', $list);
        $this->meta_title = '申请提现记录';
        $this->display();
    }

    /**
     * 店铺提现申请处理
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function storeEdit(){
        $id = trim(I('get.id'));
        $data = M('StoreWithdraw')->find($id);
        $member_id = $member_id = M('Seller')->where(array('store_id'=>$data['store_id']))->getField('member_id');
        $store_row=M('StoreApply')->where(array('member_id'=>$member_id))->field('settlement_bank_account_name,settlement_bank_account_number,store_name')->find();
        $data['bank_name'] = $store_row['settlement_bank_account_name'];
        $data['bank_account'] = $store_row['settlement_bank_account_number'];
        $data['store_name'] = $store_row['store_name'];
        $this->assign('data',$data);
        $this->assign('status',get_store_withdraw_text());
        $this->display();
    }

    /**
     * 店铺提现
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function storeUpdate(){
        $status = trim(I('post.status'));
        if ( ($status == '101' || $status == '201') && empty(I('post.remark')) ) {
            $this->error('拒绝原因不能为空');
        }
        $data['id'] = trim(I('post.id'));
        switch($status){
          case '101':
            $data['admin_refuse_time'] = NOW_TIME;
            $data['status'] = 2;
            $data['remark'] = trim(I('post.remark'));
            break;
          case '200':
            $data['bank_time'] = NOW_TIME;
            $data['status'] = 3;
            $data['fee'] = trim(I('post.fee'));
            if (!is_numeric($data['fee'])) {
                $this->error('请输入数值');
            }
            if ($data['fee'] < 0.01 && $data['fee'] != '0.00') {
                $this->error('输入金额过小');
            }
            break;
          case '201':
            $data['bank_refuse_time'] = NOW_TIME;
            $data['status'] =4;
            $data['remark'] = trim(I('post.remark'));
            break;
          case '300':
            $data['success_time'] = NOW_TIME;
            $data['status'] =5;
            break;
        }
        $StoreWithdraw = M('StoreWithdraw');
        //开启事务
        $StoreWithdraw->startTrans();
        $res = $StoreWithdraw->save($data);
        //查询商户现金申请时间
        $ctime = $StoreWithdraw->where('id='.$data['id'])->getField('ctime');
        if ($data['status']==2 || $data['status']==4) {
            //商户流水表中更改
            $res1 = M('StoreCash')->where(array('ctime'=>$ctime))->setField('status','0');
            if ($res !== false && $res1 !== false) {
                $StoreWithdraw->commit();
                $this->success('操作成功！');
            }else{
                $StoreWithdraw->rollback();
                $this->error('操作失败！');
            }
        }else{
            if ($data['status'] == 5) {
                //商户流水表中更改
                $res1 = M('StoreCash')->where(array('ctime'=>$ctime))->setField('status','1');
                if ($res !== false && $res1 !== false) {
                    $StoreWithdraw->commit();
                    $this->success('操作成功！');
                }else{
                    $StoreWithdraw->rollback();
                    $this->error('操作失败！');
                }
            }else{
                if ($res !== false) {
                    $StoreWithdraw->commit();
                    $this->success('操作成功！');
                }else{
                    $StoreWithdraw->rollback();
                    $this->error('操作失败！');
                }
            }
        }
    }

    /**
     * 店铺详细信息（从申请入驻信息中读取）
     */
    public function detail(){
        if(IS_POST){
            $data = I('post.');
            $map['id'] = array('not in',$data['id']);
            $store_name = M('store_apply')->where($map)->getField('store_name',true);
            if(in_array($data['store_name'],$store_name)){
                $this->error('该店铺名已存在！');
            }
            $rs =  D('Store')->update($data);
            $rs !== false ? $this->success('修改成功') : $this->error('修改失败') ;
        }
        $member_id = I('get.member_id');
        $urlType = I('get.urlType','index');
        empty($member_id) && $this->error('参数错误！');
        $data = D('Store')->info($member_id);
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $this->meta_title = '店铺信息';
        $this->member_id = $member_id;
        $this->assign('urlType',$urlType);
        $this->assign('data',$data);
        $this->display();
    }
    
    
    /**
     * 更新、编辑处理
     */
    public function editHandle(){
        if(IS_POST){
            $store = D('Store');
            if($store->create()){
                $store->end_time = strtotime(I('post.end_time'));
                //开启事务 buddha 20170621 店铺修改名称 及其店铺等级
                $Store = M('Store');
                $Store->startTrans();  
                $rst = $store->where(array('store_id'=>I('store_id')))->save();
                if(I('store_id') && I('store_name') ) {
                    $data = array('store_name'=>I('store_name'),'grade_id'=>I('grade_id'));
                    $res = M('StoreApply')->where(array('store_id' => I('store_id')))->setField($data);
                }else{
                        $res =true;
                    }
                if($rst !== false && $res!==false){
                    //提交事务
                    $Store->commit();

                    //记录行为
                    action_log('edit_store', 'store', I('store_id'), UID);
                    $this->success('更新成功！',U('index'));
                }else{
                    //事务回滚
                    $Store->rollback();
                    $this->error('更新失败！');
                }
            }else{
                $this->error($store->getError());
            }
        }
    }
    
    
    /**
     * 设置店铺状态
     * @see \Admin\Controller\AdminController::setStatus()
     */
    public function setStatus(){
        $id = I('id');
        $status = I('status');
        if(empty($id) || $status=='') $this->error('系统参数异常！');
        $map['store_id'] = array('eq',$id);
        $rst = M('Store')->where($map)->setField('status',$status);
        $where['store_id'] = $id;
        if($status == 1){
            $where['status'] = -3;
            M('Item')->where($where)->setField('status', 1);
        }else{
            $where['status'] = 1;
            M('Item')->where($where)->setField('status', -3);
        }

        if($rst !== false){
            //记录行为
            action_log('set_status', 'store', $id, UID);
            $this->success('操作成功！');
        }else{
            $this->error('操作失败！');
        }
    }
    
    
    /**
     * 经营类目
     */
    public function sellCategory(){
        $store_id = I('id');
        $store_id || $this->error('请选择店铺！');
        $map['store_id'] = array('eq',$store_id);
        $field = 'id,rate,sell_cid_1,sell_cid_2,sell_cid_3';
        $lists = D('Store')->sellCategory($map,$field);
        $map  = array('status' => array('gt', -1));
        $itemCategory = M('item_category')->where($map)->field('id,name')->select();
        $newArr = array();
        foreach ($itemCategory as $key=>$val){
            $newArr[$val['id']] = $val['name'];
        }
        //店铺信息
        $store_field = 'store_id,store_name';
        $store = M('store')->where(array('store_id'=>$store_id,))->field($store_field)->find();
        $this->assign('list',$lists);
        $this->assign('store',$store);
        $this->assign('itemCategory',$newArr);
        $this->meta_title = '店铺经营类目';
        $this->display();
    }
    
    
    /**
     * 保存店铺经营类目
     */
    public function saveSellCategory(){
        $data['store_id'] = I('store_id');
        $data['rate'] = I('rate');
        $data['sell_cid_1'] = I('cid_1');
        $data['sell_cid_2'] = I('cid_2');
        $data['sell_cid_3'] = I('cid_3');
        //数据判断
        $data['sell_cid_1'] || $this->error('请选择经营类目！');
        $data['store_id'] || $this->error('请选择店铺！');
        //$data['rate'] || $this->error('佣金比例必须填写！');
        
        
        $map['store_id'] = $data['store_id'];
        $map['sell_cid_1'] = $data['sell_cid_1'];
        $map['sell_cid_2'] = $data['sell_cid_2'];
        $map['sell_cid_3'] = $data['sell_cid_3'];
        $isExist = M('store_sell_category')->where($map)->find();
        if($isExist){
            $this->error('此分类已选择！');
        }
        $rst = M('store_sell_category')->add($data);
        
        $res = $this->addStoreApply($data);

        if($rst !== false && $res !== false){
            action_log('add_sell_category', 'store_sell_category', $data['store_id'], UID);
            // 清理缓存
            S('typeData_itemCategory_cache_'.$data['store_id'],null);
            $this->success('添加成功！',U('sellCategory',array('id'=>I('store_id'))));
        }else{
            $this->error('添加失败！');
        }
    }
    
    /**
     * 保存店铺经营类目，同步增加店铺申请表
     * @author buddha <[email address]>
     * @param  [type] $data [description]
     */
    public function addStoreApply( $data ){
        //查询店铺申请表中经营类目
        $info = M('store_apply')->where(array('store_id'=>$data['store_id']))->field('store_class_ids,store_class_names')->find();
        $sell_class_name = unserialize($info['store_class_names']);
        $sell_class_ids = unserialize($info['store_class_ids']);
        //新增的经营类目ID
        $add_ids = $data['sell_cid_1'] . ',' .$data['sell_cid_2'] . ',' . $data['sell_cid_3'];
        //新增的经营类目名称
        $add_cid_1_name = getCategoryNameById($data['sell_cid_1']);
        if ($data['sell_cid_2']) {
            $add_cid_2_name = getCategoryNameById($data['sell_cid_2']);
        }else{
            $add_cid_2_name = '全部';
        }
        if ($data['sell_cid_3']) {
            $add_cid_3_name = getCategoryNameById($data['sell_cid_3']);
        }else{
            $add_cid_3_name = '全部';
        }
        $new_names = $add_cid_1_name . ',' . $add_cid_2_name . ',' . $add_cid_3_name;
        //序列化
        array_push($sell_class_name,$new_names);
        array_push($sell_class_ids, $add_ids);

        $infos['store_class_names'] = serialize($sell_class_name);
        $infos['store_class_ids'] = serialize($sell_class_ids);

        $res = M('store_apply')->where('store_id='.$data['store_id'])->setField($infos);

        if ($res) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除经营类目
     */
    public function delSellCid(){
        $ids = (array)I('ids');
        $store_id = I('store_id');
        if( empty($ids) ) $this->error('请选择要删除的类目！');
        if( empty($store_id) ) $this->error('请选择店铺！');
        $map['store_id'] = array('eq',$store_id);
        $map['id'] = array('in',$ids);
        $model = M('store_sell_category');
        //开启事务
        $model->startTrans();
        //根据店铺商品类目查询
        $info = $model->where($map)->find();
        $rst = $model->where($map)->delete();
        $where['store_id']=$store_id;
        if ($info['sell_cid_3'] !=0) {
            $where['_string'] = "cid_3 = ".$info['sell_cid_3'];
        }else{
            if ($info['sell_cid_2'] !=0) {
               $where['_string']= "cid_2 = ".$info['sell_cid_2'];
            }else{
                $where['_string']= "cid_1 = ".$info['sell_cid_1'];
            }
        }

        $data = array(
                'status' => 0,
                'cid_1'  => 0,
                'cid_2'  => 0,
                'cid_3'  => 0
            );
        $res = M('Item')->where($where)->setField($data);
        if($rst !== false && $res !==false){
            $model->commit();
            action_log('del_sell_category', 'store_sell_category', $store_id, UID);
            // 清理缓存
            S('typeData_itemCategory_cache_'.$store_id,null);
            $this->success('已删除！',U('sellCategory',array('id'=>$store_id)));
        }else{
            $model->rollback();
            $this->error('删除失败！');
        }
    }
    
    
    /**
     * 设置分类佣金比例
     */
    public function setRate(){
        $id = I('post.id', '');
        $value = I('post.value', '');
        if(empty($id) || empty($value)){
            $this->error('参数不完整！');
        }
        if(!check_form_hash()){
            $this->error('非法数据提交！');
        }
        //查询修改的哪家店铺 start
        $store_id = M('store_sell_category')->where(array('id'=>$id))->getField('store_id');
        $member_id = M('Store')->where(array('store_id'=>$store_id))->getField('member_id');

        $store_arr = M('store_sell_category')->where(array('store_id'=>$store_id))->getField('id',true);
        $store_apply = M('store_apply')->where(array('member_id'=>$member_id))->getField('store_class_rates');
        $_rate  = explode(',',$store_apply);
        foreach ($store_arr as $k => $v) {
            if ($v == $id) {
                $_rate[$k] = $value;
            }
        }
        $_string = implode(',',$_rate);
        //查询修改的哪家店铺 end
        
        $res = M('store_sell_category')->where(array('id'=>$id))->setField('rate', $value);
        if($res){
            M('store_apply')->where(array('member_id'=>$member_id))->setField('store_class_rates',$_string);
            action_log('set_rate', 'store_sell_category', $id, UID);
            $this->success('更新成功！');
        }else{
            $this->error('更新失败！');
        }
    }
    
    
    /**
     * 店铺等级
     */
    public function grade(){
        $map = array();
        $_GET['name'] && $map['name'] = array('like','%'.I('get.name').'%');
        $field = array('id','name','goods_limit','album_limit','price','sort','marketing');
        $order = 'id asc';
        $lists = $this->lists('store_grade', $map,$order,$field);
        //记录当前列表页的Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        int_to_string($lists, array('status' => array('0' => '<span class="text-cancel">已禁用</span>', '1' => '<span class="text-success">正常</span>')));
        $this->lists = $lists;
        $this->meta_title = '店铺等级列表';
        $this->display();
    }
    
    
    /**
     * 编辑和新增店铺等级
     */
    public function addGrade(){
        $title = $_REQUEST['id'] ? '编辑' : '新增';
        if(IS_POST){
            $rules = array(
                array('name','require','等级名称必须填写'),
                array('price','require','价格必须填写')
            );
            $Store = M('store_grade');
            if($Store->validate($rules)->create()){
                $Store->marketing = implode(',',I('post.marketing'));
                $rst = I('post.id') ? $Store->save() : $Store->add();
                $rst !==false ? $this->success($title.'成功！',U('grade')) : $this->error($title.'失败！');
            }else{
                $this->error($Store->getError());
            }
            
        }else{
            $data = array();
            if(I('get.id')){
                $data = M('store_grade')->where(array('id'=>I('get.id')))->find();
            }
            //获取平台营销管理
            $this->assign('list',C('STORE_MARKETING_LIST'));
            $data['marketing'] = explode(',',$data['marketing']);
            $this->assign('data',$data);
            $this->assign('title',$title.'店铺等级');
            $this->display();
        }
    }
    
    
    /**
     * 删除店铺等级
     * 过滤系统默认的等级
     */
    public function delGrade(){
        $ids = (array)I('ids');
        if(in_array(2,$ids)){
            $delId = array_flip($ids);
            unset($delId['1']);
            $ids = array_flip($delId);
        }
        if(empty($ids)) $this->error('请选择要操作的数据！');
        //店铺等级判断，如果此等级店铺有店铺商，不允许删除 BUDDHA 20170328
        foreach ($ids as $key => $value) {
            $count = M('Store')->where(array('grade_id'=>$value,'status'=>1))->count();
            if ($count > 0) {
                unset($ids[$key]);
            }
        }
        if(empty($ids)) $this->error('删除的店铺等级下存在加盟商户，不允许删除！');
        $map['id'] = array('in',$ids);
        $rst = M('store_grade')->where($map)->delete();
        if($rst !== false){
            action_log('del_grade', 'store_grade', $id, UID);
            $this->success('删除成功！',U('grade'));
        }else{
            $this->error('删除失败！');
        }
    }
    
    
    /**
     * 店铺分类
     */
    public function category(){
        $tree = D('Store')->category('id,pid,name,sort');
        $this->assign('tree', $tree);
        C('_SYS_GET_CATEGORY_TREE_', true); //标记系统获取分类树模板
        //记录当前列表页的Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $this->meta_title = '店铺分类';
        $this->display();
    }
    
    
    /**
     * 新增、编辑分类
     */
    public function addCategory(){
        $id = I('id');
        $title = $id ? '编辑' : '新增';
        if(IS_POST){
            $rules = array(
                array('name','require','分类名称必须填写')
            );
            $Model = M('store_category');
            if($Model->validate($rules)->create()){
                $rst = $id ? $Model->save() : $Model->add();
                $rst !== false ? $this->success($title.'成功！',U('category')) : $this->error($title.'失败！');
            }else{
                $this->error($Model->getError());
            }
        }else{
            $data = array();
            $category = array();
            if($id){
                $data = M('store_category')->where(array('id'=>$id))->find();
            }
            if(I('pid')){
                $category = M('store_category')->where(array('id'=>I('pid')))->field('id,name,pid')->find();
            }
            $this->assign('category',$category);
            $this->assign('data',$data);
            $this->meta_title = $title.'店铺分类';
            $this->display();
        }
    }
    
    
    /**
     * 删除店铺分类
     */
    public function delCategory(){
        $id = I('id');
        $id || $this->error('请选择删除分类！');
        $rst = M('store_category')->where(array('id'=>$id))->delete();
        $rst !== false ? $this->success('删除成功！') : $this->error('删除失败！');
    }
    
    
    /**
     * 店铺分类数据表
     */
    public function category_tree($tree = null){
        C('_SYS_GET_CATEGORY_TREE_') || $this->_empty();
        $this->assign('tree', $tree);
        $this->display('tree');
    }
    
    
    /**
     * 店铺二级域名管理
     */
    public function domain(){
        $map = array();
        $map['domain'] = array('neq','');
        $map['status'] = array('egt',0);
        $_GET['domain'] && $map['domain'] = array('eq',I('domain'));
        $_GET['store'] && $map['store_name'] = array('like','%'.I('store').'%');
        $order = 'time desc';
        $field = array('store_id','store_name','domain','domain_change_times','member_name');
        //记录当前列表页的Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $lists = $this->lists(CONTROLLER_NAME, $map,$order,$field);
        $this->lists = $lists;
        $this->meta_title = '二级域名列表';
        $this->display();
    }
    
    
    /**
     * 编辑二级域名
     */
    public function editDomain(){
        $id = I('id');
        if(IS_POST){
            $data['domain'] = I('domain');
            $data['domain_change_times'] = I('times');
            $data['domain'] || $this->error('请填写二级域名！');
            I('store_id') || $this->error('异常操作！');
            $rst = M('Store')->where(array('store_id'=>I('store_id')))->save($data);
            if($rst !== false){
                action_log('set_domain', 'store', $id, UID);
                $this->success('修改成功！',U('domain'));
            }else{
                $this->error('修改失败！');
            }
        }else{
            $field = array('store_id','store_name','domain','domain_change_times','member_name');
            $data = M('Store')->where(array('store_id'=>$id))->field($field)->find();
            $this->assign('data',$data);
            $this->assign('meta_title','编辑二级域名');
            $this->display();
        }
    }
    
    
    /**
     * 开店申请
     */
    public function apply(){
        $map = array();
        $status = I('get.status');
        $map['status'] = array('egt',0);
        $_GET['store']  && $map['store_name'] = array('like','%'.I('get.store').'%');
        $_GET['seller'] && $map['seller_name'] = array('like','%'.I('get.seller').'%');
        if($_GET['grade']){
            $map['grade_id'] = array('eq',I('get.grade'));
        }
        if($status != '' && $status != 'all'){
            $map['status'] = array('eq',$status);
        }
        $order = 'ctime desc';
        $field = array('id','store_id','member_id','store_name','grade_id','member_name','seller_name','ctime','status');
        $lists = $this->lists('store_apply', $map,$order,$field);

        //数据处理 将空白数据排除掉 BUDDHA 20170522
        foreach ($lists as $key => $value) {
            if (empty($value['store_name'])) {
                unset($lists[$key]);
            }
        }
        $grade = M('store_grade')->field('id,name')->order('sort desc')->select();
        $newArr = array();
        foreach ($grade as $key=>$val){
            $newArr[$val['id']] = $val['name'];
        }
        $this->assign('grade',$newArr);
        
        //记录当前列表页的Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        int_to_string($lists, array('status' => array('0' => '<span class="text-cancel">已禁用</span>', '1' => '<span class="text-success">正常</span>')));
        //display前置操作
        $this->lists = $lists;
        $this->meta_title = '申请开店列表';
        //店铺申请条数
        //$this->_page = count($lists);
        $this->display();
    }
    
    
    /**
     * 验证
     */
    public function applyVerify(){
        $type = I('verify_type');
        $member_id = I('member_id');
        $rate = I('rate');
        $joinin_message = I('joinin_message');
        $pay_message = I('paying_money_certificate_explain');
        
        // 根据审核之前的状态，处理相关操作
        $map['member_id'] = $member_id;
        $status = M('StoreApply')->where($map)->getField('status');
        // 拒绝
        if($type == 'fail'){
            if($status == 1){ //基本信息审核
                $data['status'] = 3;
                $data['joinin_message'] = $joinin_message;
            }else if($status == 4){ // 交付单审核
                $data['status'] = 5;
                $data['paying_money_certificate_explain'] = $pay_message;
            }
        // 通过
        }else if($type == 'success'){
            // TODO ：缴费证明验证
            $status = 4;

            if($status == 1){ //基本信息审核
                $data['status'] = 2;
                $data['joinin_message'] = $joinin_message;
                // 佣金比例限制
                if(empty($rate)){
                    $this->error('请设置营销类目佣金');
                }
                $data['store_class_rates'] = implode(',',$rate);
            }else if($status == 4){ // 审核成功，允许开店
                $data['status'] = 6;
                $data['paying_money_certificate_explain'] = $pay_message;
            }
        }
        //允许开店
        if($data['status'] == 6){
            $model = M('StoreApply');
            // 佣金比例限制
            if(empty($rate)){
                $this->error('请设置营销类目佣金');
            }
            $data['store_class_rates'] = implode(',',$rate);
            $info = $model->where($map)->find();
            $model->startTrans();
            $res = $model->where($map)->save($data);
            if($res !== false){ //开通店铺
                $sdata['store_name'] = $info['store_name'];
                $sdata['grade_id'] = $info['grade_id'];
                $sdata['member_id'] = $info['member_id'];
                $sdata['member_name'] = $info['member_name'];
                $sdata['seller_name'] = $info['seller_name'];
                $sdata['tel'] = $info['contacts_phone'];
                $sdata['status'] = 1;
                $sdata['time'] = time();
                // 店铺默认幻灯片
                $sdata['slide'] = '0,0,0,0,0';
                $sdata['slide_url'] = ',,,,';
                //默认店铺到期时间为一年
                $sdata['end_time'] = time()+31536000;
                $res = M('Store')->add($sdata);
                //修改开店申请表中店铺字段 BUDDHA 20170321
                $model->where(array('member_id'=>$info['member_id']))->setField('store_id',$res);
                if($res){  // 添加店铺经营类目
                    $cate = unserialize($info['store_class_ids']);
                    $store_id = $res;
                    $sellCate = array();
                    $classRate = explode(',',$data['store_class_rates']);
                    foreach ($cate as $key=>$val){
                        $category = explode(',',$val);
                        $sellCate[$key]['store_id'] = $store_id;
                        //$sellCate[$key]['rate'] = isset($classRate[$key])? $classRate[$key] : '';
                        $sellCate[$key]['rate'] = 0;
                        $sellCate[$key]['sell_cid_1'] = $category[0];
                        $sellCate[$key]['sell_cid_2'] = $category[1];
                        $sellCate[$key]['sell_cid_3'] = ( $category[2] != NULL ) ? $category[2] : 0;
                    }
                    $res = M('StoreSellCategory')->addAll($sellCate);
                    if($res){
                        // 添加卖家用户表
                        $sellData['seller_name'] = $info['seller_name'];
                        $sellData['member_id'] = $info['member_id'];
                        $sellData['store_id'] = $store_id;
                        $res = M('Seller')->add($sellData);
                        if($res){
                            M('Store')->where('store_id='.$store_id)->save(array('rate' => $rate));
                            $model->commit();
                        }else{
                            $model->rollback();
                        }
                    }else{
                        $model->rollback();
                    }
                }else{
                    $model->rollback();
                }
            }else{
                $model->rollback();
            }
        }else{
            $res = M('StoreApply')->where($map)->save($data);
        }
        $res !== false ? $this->success('操作成功！',U('Store/apply')) : $this->error('操作失败！');
    }
    
    
    /**
     * 店铺消息列表
     */
    public function message(){
        $model = D('StoreMessage');
        $map['status'] = array('egt',0);
        $order = ' `ctime` DESC';
        $field = true;
        $lists = $this->lists($model,$map,$order,$field);
        $this->assign('lists',$lists);
        $this->display();
    }
    
    /**
     * 添加店铺消息
     * @author buddha <[email address]>
     */
    public function addMsg(){
        if(IS_POST && IS_AJAX){
            $rules = array(
                array('title', 'require', '消息标题不能为空', 1, 'regex', 3),
                array('content', '10,8000', '消息内容至少10个字哦！', 1, 'length', 3),
                array('send_confirm', 'require', '请确认发送！', 1, 'regex', 3),
            );
            $model = M('StoreMessage');
            if(!$model->validate($rules)->create()){
                $this->error($model->getError());
            }
            $data['uid'] = UID;
            $data['to_store'] = I('to_store') ? : 0;
            $data['title'] = I('title');
            $data['content'] = I('content');
            $data['ctime'] = NOW_TIME;
            $rst = $model->add($data);
            if($rst){
                $this->success('发送成功');
            }else{
                $this->error('发送失败！');
            }
        }
        $this->meta_title = '发布店铺通知';
        $this->assign('uid',UID);
        $this->display();
    }
    
    /**
     * 查看店铺消息详情
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function detailMsg(){
        $id = I('get.id');
        $data = M('StoreMessage')->where(array('status'=>1,'id'=>$id))->find();
        if(empty($data)){
            $this->error('消息不存在！');
        }
        $this->data = $data;
        $this->meta_title = '消息详情';
        $this->display();
    }

    /**
     * 设置店铺消息状态
     */
    public function setMsgStatus($method = null){
        $id = array_unique((array) I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        if(empty($id)){
            $this->error('请选择要操作的数据!');
        }
        switch(strtolower($method)){
            case 'deletemsg':
                $map['id'] = array('in',$id);
                $status = M('StoreMessage')->where($map)->setField('status',-1);
                if($status){
                    $this->success('删除成功');
                }
                $this->error('删除失败');
                break;
            default:
                $this->error('参数非法');
        }
    }

    /**
     * 通过经纬度获取具体地址
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    function getAddresInfoByLngLat(){
        $lat = I('post.lat');
        $lng = I('post.lng');
        //调用函数
        $res = getLocationLatLng($lat,$lng);
        $this->ajaxReturn($res);
    }
}